package com.ysxsoft.wdg.ui.fragment;

import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.home.ZyGoodsAdapter;
import com.ysxsoft.wdg.base.BaseFragment;
import com.ysxsoft.wdg.base.BaseGWebViewActivity;
import com.ysxsoft.wdg.bean.BannerBean;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.response.TopAdResponse;
import com.ysxsoft.wdg.bean.zy.GoodsBean;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.MainActivity;
import com.ysxsoft.wdg.ui.activity.center_zy.ClassifyActivity;
import com.ysxsoft.wdg.ui.activity.center_zy.GoodsDetailActivity;
import com.ysxsoft.wdg.ui.activity.center_zy.ZyCateListActivity;
import com.ysxsoft.wdg.ui.activity.center_zy.ZyHotActivity;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.banner.BannerRoundImageLoader;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

public class ZyFragment extends BaseFragment implements OnRefreshListener,OnLoadmoreListener{


    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.iv0)
    ImageView iv0;
    @BindView(R.id.tv0)
    TextView tv0;
    @BindView(R.id.iv1)
    ImageView iv1;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.iv2)
    ImageView iv2;
    @BindView(R.id.tv2)
    TextView tv2;
    @BindView(R.id.iv3)
    ImageView iv3;
    @BindView(R.id.tv3)
    TextView tv3;
    @BindView(R.id.iv4)
    ImageView iv4;
    @BindView(R.id.tv4)
    TextView tv4;
    @BindView(R.id.iv5)
    ImageView iv5;
    @BindView(R.id.tv5)
    TextView tv5;
    @BindView(R.id.iv6)
    ImageView iv6;
    @BindView(R.id.tv6)
    TextView tv6;
    @BindView(R.id.iv7)
    ImageView iv7;
    @BindView(R.id.tv7)
    TextView tv7;
    @BindView(R.id.iv_ms)
    ImageView ivMs;
    @BindView(R.id.iv_new)
    ImageView ivNew;
    @BindView(R.id.iv_find)
    ImageView ivFind;
    @BindView(R.id.iv_gg)
    ImageView ivGg;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private TextView[] tvs;
    private ImageView[] ivs;
    private int[] ivIds;

    private ZyGoodsAdapter mAdapter;
    private int page = 1;
    private List<BannerBean> cateList = new ArrayList<>();
    private String uid = "";
    private String id1,id2,id3,content4;



    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fm_zy;
    }

    @Override
    protected void initData() {
        banner.setImageLoader(new BannerRoundImageLoader());
        uid = SharePrefUtils.getUserId();

        iv7.setImageResource(R.mipmap.zy8);
        tv7.setText("分类");

        tvs = new TextView[]{tv0,tv1,tv2,tv3,tv4,tv5,tv6};
        ivs = new ImageView[]{iv0,iv1,iv2,iv3,iv4,iv5,iv6};

        getHomeCate();


        ivMs.setImageResource(R.mipmap.zy_ms);
        ivNew.setImageResource(R.mipmap.zy_new);
        ivFind.setImageResource(R.mipmap.zy_find);

        recyclerview.setFocusable(false);
        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        mAdapter = new ZyGoodsAdapter(R.layout.item_goods);
        recyclerview.setAdapter(mAdapter);

        onRefresh(refreshLayout);

        getTopAd();
        getBottomAd();
    }

    private void getHomeCate() {
        mApiHelper.getZyCate(new Observer<BaseBean<List<BannerBean>>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<List<BannerBean>> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    cateList = baseBean.getData();
                    for (int i = 0; i < cateList.size(); i++) {
                        ViewUtils.loadCircleImage(mContext,cateList.get(i).getPic(),ivs[i]);
                        tvs[i].setText(cateList.get(i).getTitle());
                    }
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getBanner() {
        mApiHelper.getZyBanner(new Observer<BaseBean<List<BannerBean>>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<List<BannerBean>> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    List<BannerBean> bannerBeans = baseBean.getData();
                    List<String> list = new ArrayList<>();
                    if (bannerBeans.size() > 0) {
                        for (int i = 0; i < bannerBeans.size(); i++) {
                            list.add(bannerBeans.get(i).getPic());
                        }
                        banner.setImages(list);
                        banner.start();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void setListener() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsDetailActivity.start(mContext,mAdapter.getItem(position).getId());
            }
        });

    }


    @OnClick({R.id.ll7, R.id.iv_ms, R.id.iv_new, R.id.iv_find,
            R.id.iv_gg, R.id.tv_hot})
    public void onViewClicked1(View view) {
        switch (view.getId()) {
            case R.id.ll7:
                ClassifyActivity.start(mContext);
                break;
            case R.id.iv_ms://限时秒杀
                GoodsDetailActivity.start(getActivity(),id1);
                break;
            case R.id.iv_new://新品好货
                GoodsDetailActivity.start(getActivity(),id2);
                break;
            case R.id.iv_find://发现好货
                GoodsDetailActivity.start(getActivity(),id3);
                break;
            case R.id.iv_gg://广告
//                BaseGWebViewActivity.start(getActivity(),"广告",content4);
                MainActivity activity= (MainActivity) getActivity();
                activity.showTPage();
                break;
            case R.id.tv_hot:
                ZyHotActivity.start(mContext);
                break;
        }
    }
    @OnClick({R.id.ll0, R.id.ll1, R.id.ll2, R.id.ll3,
            R.id.ll4, R.id.ll5, R.id.ll6})
    public void onViewClicked(View view) {
        int catePosition = 0;
        switch (view.getId()) {
            case R.id.ll0:
                catePosition = 0;
            break;
            case R.id.ll1:
                catePosition = 1;
                break;
            case R.id.ll2:
                catePosition = 2;
                break;
            case R.id.ll3:
                catePosition = 3;
                break;
            case R.id.ll4:
                catePosition = 4;
                break;
            case R.id.ll5:
                catePosition = 5;
                break;
            case R.id.ll6:
                catePosition = 6;
                break;
        }

        if (catePosition < cateList.size()){
            BannerBean cateBean = cateList.get(catePosition);
            ZyCateListActivity.start(mContext,cateBean.getTitle(),cateBean.getId(),true);
        }else {
            ToastUtils.showToast("敬请期待");
        }
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.finishLoadmore(600);
        page++;
        getHotList();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.finishRefresh(600);
        getBanner();
        page = 1;
        mAdapter.clear();
        getHotList();

        getTopAd();
        getBottomAd();
    }

    private void getHotList() {
        mApiHelper.getZyHotList(page + "", "0", "", "0",uid, new Observer<BaseBean<List<GoodsBean>>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseBean<List<GoodsBean>> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    if (page == 1){
                        mAdapter.setNewData(baseBean.getData());
                    }else {
                        mAdapter.addData(baseBean.getData());
                    }
                }else {
                    if (page != 1){
                        ToastUtils.showToast(baseBean.getMs());
                    }
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    /**
     * 获取顶部广告
     */
    private void getTopAd() {
        OkHttpUtils.post()
                .url(UrlHost.MAIN_AD)
                .addParams("type",  "0")//0：上边3个是   1：下边1个
                .addParams("style","3")	//1首页3自营2实体
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    TopAdResponse messageBean = JsonUtils.parseByGson(response, TopAdResponse.class);
                    if (messageBean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(messageBean.getCode())) {
                        List<TopAdResponse.DataBean> list = messageBean.getData();
                        if(list.size()==3){
                            Glide.with(getActivity()).load(list.get(0).getPic()).into(ivMs);
                            Glide.with(getActivity()).load(list.get(1).getPic()).into(ivNew);
                            Glide.with(getActivity()).load(list.get(2).getPic()).into(ivFind);
                            id1=""+list.get(0).getGoodsid();
                            id2=""+list.get(1).getGoodsid();
                            id3=""+list.get(2).getGoodsid();
                        }
                    }
                } else {
                }
            }
        });
    }

    /**
     * 获取顶部广告
     */
    private void getBottomAd() {
        OkHttpUtils.post()
                .url(UrlHost.MAIN_AD)
                .addParams("type",  "1")//0：上边3个是   1：下边1个
                .addParams("style","3")	//1首页3自营2实体
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    TopAdResponse messageBean = JsonUtils.parseByGson(response, TopAdResponse.class);
                    if (messageBean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(messageBean.getCode())) {
                        List<TopAdResponse.DataBean> list = messageBean.getData();
                        if(list.size()==1){
                            Glide.with(getActivity()).load(list.get(0).getPic()).into(ivGg);
                            content4=list.get(0).getContent();
                        }
                    }
                } else {
                }
            }
        });
    }
}
